package org.chench.extra;

import org.zeromq.ZContext;
import org.zeromq.ZMQ;

import java.util.StringTokenizer;

/**
 * 创建"订阅"模式Socket
 * @author chench9@lenovo.com
 * @desc org.chench.extra.SubClient
 * @date 3/20/19 11:28 AM
 */
public class SubClient {
    public static void main(String[] args) {
        startSubClient();
    }

    private static void startSubClient() {
        try (ZContext context = new ZContext()){
            // 创建"订阅"模式的Socket
            ZMQ.Socket subscriber = context.createSocket(ZMQ.SUB);
            // 设置一个Socket标示,当subscriber重新连接之后可以从上次中断的地方读取到终断之后错过的数据
            //subscriber.setConnectRid(String.valueOf(new Random().nextInt(100))); // 在Java中暂时还不支持
            subscriber.connect("tcp://localhost:5555");

            // 订阅指定主题的消息
            String topic = "10000";
            subscriber.subscribe(topic.getBytes());

            while(!Thread.currentThread().isInterrupted()) {
                String string = subscriber.recvStr(0).trim();
                StringTokenizer sscanf = new StringTokenizer(string, " ");
                int zipcode = Integer.valueOf(sscanf.nextToken());
                int temperature = Integer.valueOf(sscanf.nextToken());
                int relhumidity = Integer.valueOf(sscanf.nextToken());
                System.out.println(String.format("zipcode: %s, temperature: %s, relhumidity: %s", zipcode, temperature, relhumidity));
            }
        }
    }
}
